package com.mallcai.bigdata.ladon.utils;

import com.mallcai.bigdata.ladon.dpl.entity.common.Datasource;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;

import static com.google.common.base.Preconditions.checkNotNull;

/**
 * @author feixy
 * @version 1.0
 * @date 2019-07-19 08:34
 */
@Slf4j
public class DataSourceUtils {

    /**
     * 释放资源
     * @param
     */
    public static void release(AutoCloseable... closeables){
        for (AutoCloseable closeable : closeables){
            if(closeable != null){
                try {
                    closeable.close();
                }catch (Throwable e){
                    // 防御性错误
                    log.error("关闭资源失败,msg:{}",e.getMessage(), e);
                }
            }
        }
    }


    /**
     * 测试数据源
     * @param datasource
     * @return
     */
    public static boolean test(Datasource datasource){
        String driver = checkNotNull(datasource.getJdbcDriver(), "JDBC驱动名称不能为空");
        String url = checkNotNull(datasource.getJdbcUrl(), "URL不能为空");
        String userName = getValueWithDefault(datasource.getUsername(), "");
        String password = getValueWithDefault(datasource.getPassword(), "");
        String testSql = getValueWithDefault(datasource.getTestSql(), "select 1");

        try{
            Class.forName(driver);
            try(Connection connection = DriverManager.getConnection(url, userName, password);
                Statement statement = connection.createStatement()){
                statement.setQueryTimeout(10);
                statement.executeQuery(testSql);
                log.info("数据源连接测试成功");
                return true;
            }
        }catch(Exception e){
            log.error("数据库连接测试失败", e);
            return false;
        }
    }

    private static String getValueWithDefault(String value, String defaultValue) {
        return StringUtils.isNotEmpty(value) ? value : defaultValue;
    }

}
